package com.example.javawebdemo.jdbc;

import com.example.javawebdemo.utils.DBUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

/*
1.单例模式 (Singleton)
 */


public class JDBCTemplateSingleton {
    private static class Holder {
        private static final JDBCTemplateSingleton INSTANCE = new JDBCTemplateSingleton();
    }

    private final JdbcTemplate jdbcTemplate;
    private final TransactionTemplate transactionTemplate;

    private JDBCTemplateSingleton() {
        this.jdbcTemplate = new JdbcTemplate(DBUtil.getDataSource());
        PlatformTransactionManager txManager =
                new DataSourceTransactionManager(DBUtil.getDataSource());
        this.transactionTemplate = new TransactionTemplate(txManager);
    }

    public static JdbcTemplate getJdbcTemplate() {
        return Holder.INSTANCE.jdbcTemplate;
    }

    public static TransactionTemplate getTransactionTemplate() {
        return Holder.INSTANCE.transactionTemplate;
    }
}
